#include <stdio.h>
#include <stdlib.h>

/*
    单循环链表
        1. 初始化链表
        2. 增加结点(头插法，尾插法)
        3. 删除结点
        4. 遍历链表
*/

#define true 1
#define false 0

typedef struct Node
{
    int data;
    struct Node* next;
}Node;

Node* initList()
{
    Node* L = (Node *)malloc(sizeof(Node));
    L->data = 0;
    L->next = L;// 指向自己
    return L;// 返回头节点
}

void headInsert(Node * L, int data)
{
    Node* node = (Node *)malloc(sizeof(Node));
    node->data = data;
    node->next = L->next;
    L->next = node;
    L->data++;
}

void tailInsert(Node * L, int data)
{
    Node* n = L;
    Node* newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;
    while(n->next != L)
    {
        n = n->next;
    }
    newNode->next = L;
    n->next = newNode;
}

int delete(Node * L, int data)
{
    Node* preNode = L;
    Node* node = L->next;
    while(node != L)
    {
        if (node->data == data)
        {
            // 删除操作
            preNode->next = node->next;
            free(node);
            return true;
        }
        preNode = node;
        node = node->next;
    }
    return false;
}

void printList(Node* L)
{
    Node* node = L->next;
    while(node != L)
    {
        printf("%d->", node->data);
        node = node->next;
    }
    printf("NULL\n");
}


int main()
{
    Node* L = initList();
    headInsert(L, 1);
    headInsert(L, 2);
    headInsert(L, 3);
    headInsert(L, 4);
    headInsert(L, 5);
    tailInsert(L, 6);
    delete(L, 4);
    printList(L);

    return 0;
}